<template>
  <div class="lost-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true">
        <el-form-item label="物品名称">
          <el-input v-model="searchParams.itemName" placeholder="输入名称" clearable />
        </el-form-item>
        <el-form-item label="丢失地点">
          <el-input v-model="searchParams.lostLocation" placeholder="输入地点" clearable />
        </el-form-item>
        <el-form-item label="丢失时间">
          <el-date-picker
            v-model="searchParams.lostTime"
            type="datetime"
            placeholder="选择时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchParams.username" placeholder="输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 错误提示 -->
    <el-alert v-if="error" :title="error" type="error" show-icon class="error-alert" />

    <!-- 卡片列表 -->
    <div class="card-list">
      <el-card 
        v-for="item in tableData" 
        :key="item.id" 
        class="item-card"
        @click="showDetail(item)"
      >
        <div class="card-content">
          <div class="card-image">
            <el-image
              style="width: 100px; height: 100px"
              :src="getImageUrl(item.image)"
              fit="cover"
              v-if="item.image"
            />
            <div v-else class="no-image">无图片</div>
          </div>
          <div class="card-info">
            <div class="item-name">{{ item.itemName }}</div>
            <div class="item-category">类别: {{ item.itemCategory }}</div>
            <div class="item-location">丢失地点: {{ item.lostLocation }}</div>
            <div class="item-time">丢失时间: {{ formatDate(item.lostTime) }}</div>
            <div class="item-locate">送达地点: {{ item.locate }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.size"
      :total="pagination.total"
      :page-sizes="[5, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="loadData"
      @current-change="loadData"
    />

    <!-- 详情对话框 -->
    <el-dialog 
      v-model="detailVisible" 
      :title="`物品详情 - ${currentItem?.itemName}`" 
      width="50%"
    >
      <div v-if="currentItem" class="detail-container">
        <div class="detail-image">
          <el-image
            style="width: 200px; height: 200px"
            :src="getImageUrl(currentItem.image)"
            fit="cover"
            v-if="currentItem.image"
          />
          <div v-else class="no-image">无图片</div>
        </div>
        <div class="detail-info">
          <div class="detail-row">
            <span class="detail-label">物品名称:</span>
            <span>{{ currentItem.itemName }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">物品类别:</span>
            <span>{{ currentItem.itemCategory }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">丢失地点:</span>
            <span>{{ currentItem.lostLocation }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">丢失时间:</span>
            <span>{{ formatDate(currentItem.lostTime) }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">详细描述:</span>
            <span>{{ currentItem.detailedDescription }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">送达地点:</span>
            <span>{{ currentItem.locate }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">发布人:</span>
            <span>{{ currentItem.username }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">姓名:</span>
            <span>{{ currentItem.fullName }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">手机:</span>
            <span>{{ currentItem.phone }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">创建时间:</span>
            <span>{{ formatDate(currentItem.createdAt) }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

interface LostItemDTO {
  id: number
  createdAt: string
  itemName: string
  itemCategory: string
  lostLocation: string
  lostTime: string
  detailedDescription: string
  image: string | null
  locate: string
  username: string
  fullName: string
  phone: string
}

// 表格数据
const tableData = ref<LostItemDTO[]>([])
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 搜索参数
const searchParams = reactive({
  itemName: '',
  lostLocation: '',
  lostTime: '',
  username: ''
})

// 详情对话框
const detailVisible = ref(false)
const currentItem = ref<LostItemDTO | null>(null)

const loading = ref(false)
const error = ref('')

// 日期格式化
const formatDate = (dateString: string) => {
  if (!dateString) return '无日期'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取图片完整URL
const getImageUrl = (path: string | null) => {
  if (!path) return ''
  if (path.startsWith('http')) return path
  return `http://localhost:8080/${path}`
}

// 显示详情
const showDetail = (item: LostItemDTO) => {
  currentItem.value = item
  detailVisible.value = true
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const params = {
      page: pagination.current,
      pageSize: pagination.size,
      itemName: searchParams.itemName || undefined,
      lostLocation: searchParams.lostLocation || undefined,
      lostTime: searchParams.lostTime || undefined,
      username: searchParams.username || undefined
    }
    
    const token = localStorage.getItem('token')
    const headers = token ? { Authorization: `Bearer ${token}` } : {}
    
    const response = await axios.get('/lost/page', {
      params,
      headers
    })
    
    if (response.data?.data) {
      tableData.value = response.data.data
      pagination.total = response.data.total || 0
    } else {
      throw new Error('无效的响应结构')
    }
  } catch (err: any) {
    console.error('数据加载失败', err)
    
    if (axios.isAxiosError(err)) {
      if (err.response) {
        switch (err.response.status) {
          case 401:
            error.value = '未授权，请登录'
            break
          case 403:
            error.value = '访问被拒绝，请联系管理员'
            break
          case 404:
            error.value = '请求的资源不存在'
            break
          case 500:
            error.value = '服务器内部错误，请稍后再试'
            break
          default:
            error.value = `请求错误: ${err.response.status}`
        }
        
        if (err.response.data?.message) {
          error.value += `: ${err.response.data.message}`
        }
      } else {
        error.value = `网络错误: ${err.message}`
      }
    } else {
      error.value = `未知错误: ${err.message || '请检查控制台获取更多信息'}`
    }
    
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchParams, {
    itemName: '',
    lostLocation: '',
    lostTime: '',
    username: ''
  })
  loadData()
}

// 初始化加载
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.lost-container {
  margin-top: 70px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

/* 卡片列表样式 */
.card-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.item-card {
  cursor: pointer;
  transition: all 0.3s ease;
  height: 100%;
}

.item-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  padding: 10px;
}

.card-image {
  flex: 0 0 100px;
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-info {
  flex: 1;
}

.item-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.item-category, .item-location, .item-time, .item-locate {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
  line-height: 1.4;
}

.no-image {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}

/* 详情对话框样式 */
.detail-container {
  display: flex;
}

.detail-image {
  flex: 0 0 200px;
  margin-right: 20px;
}

.detail-info {
  flex: 1;
}

.detail-row {
  margin-bottom: 15px;
  display: flex;
}

.detail-label {
  font-weight: bold;
  color: #333;
  width: 100px;
  flex-shrink: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}

.error-alert {
  margin-bottom: 20px;
}
</style>